﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using Emgu.CV;

namespace MCYFlashApp
{
    public partial class FrmMaim : Form
    {
        XmlFile _XmlFile;
        List<SwfFile> _lstFile;
        FrmSwf _frmswf = new FrmSwf();
        PlayControl _player = new PlayControl();

        private MouseKeyHook mouseKeyHook1 = new MouseKeyHook(true, true);//鼠标，键盘  


        private VideoCapture _capture = null;
        private Mat _frame;
        Mat _forgroundMask = new Mat();
        private MotionHistory _motionHistory;
        private IBackgroundSubtractor _forgroundDetector;
        public FrmMaim()
        {
            InitializeComponent();

            _XmlFile = new XmlFile();
            _lstFile = new List<SwfFile>();

            try
            {
                txtTime.Value = decimal.Parse(ConfigurationManager.AppSettings["PlayTime"]);
                _player.PlayTime = (int)txtTime.Value;

                CvInvoke.UseOpenCL = false;
                _capture = new VideoCapture();
                _motionHistory = new MotionHistory(0.5, 0.05, 0.5);
                _forgroundDetector = new BackgroundSubtractorMOG2();
                _capture.ImageGrabbed += ProcessFrame;
                _frame = new Mat();
                //Application.Idle += ProcessFrame;
            }
            catch
            {

            }

            mouseKeyHook1.KeyDown += new KeyEventHandler(Form1_KeyDown);
            //mouseKeyHook1.KeyPress += new KeyPressEventHandler(mouseKeyHook1_KeyPress);  
            //mouseKeyHook1.KeyUp += new KeyEventHandler(mouseKeyHook1_KeyUp);  
            //mouseKeyHook1.OnMouseActivity += new MouseEventHandler(Form1_MouseDown);  
        }

        #region "captureI"
        private void ProcessFrame(object sender, EventArgs arg)
        {
            if (_capture != null && _capture.Ptr != IntPtr.Zero)
            {
                _capture.Retrieve(_frame, 0);

                //CvInvoke.CvtColor(_frame, _grayFrame, ColorConversion.Bgr2Gray);

                //CvInvoke.PyrDown(_grayFrame, _smallGrayFrame);

                //CvInvoke.PyrUp(_smallGrayFrame, _smoothedGrayFrame);

                //CvInvoke.Canny(_smoothedGrayFrame, _cannyFrame, 100, 60);
                _forgroundDetector.Apply(_frame, _forgroundMask);

                //update the motion history
                _motionHistory.Update(_forgroundMask);
                captureImageBox.Image = _forgroundMask;

                //grayscaleImageBox.Image = _grayFrame;
                //smoothedGrayscaleImageBox.Image = _smoothedGrayFrame;
                //cannyImageBox.Image = _cannyFrame;
            }
        }

        private void ReleaseData()
        {
            if (_capture != null)
                _capture.Dispose();
        }
        #endregion

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyData)
            {
                case Keys.Up:
                    _player.PlayBefor();
                    break;
                case Keys.Down:
                    _player.PlayAfter();
                    break;
                //case Keys.B:
                //    MouseFlag.MouseLefClickEvent(9, 1059, 0);
                //    break;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                this.WindowState = FormWindowState.Minimized;
                this.notifyIcon1.Visible = true;
                this.Hide();
            }
            else
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }

        private void FrmMaim_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 注意判断关闭事件reason来源于窗体按钮，否则用菜单退出时无法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                //取消"关闭窗口"事件
                e.Cancel = true; // 取消关闭窗体 

                //使关闭时窗口向右下角缩小的效果
                this.WindowState = FormWindowState.Minimized;
                this.notifyIcon1.Visible = true;
                //this.m_cartoonForm.CartoonClose();
                this.Hide();
                return;
            }
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.notifyIcon1.Visible = true;
            this.Show();
            this.Activate();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("你确定要退出？", "系统提示",
                MessageBoxButtons.YesNo, MessageBoxIcon.Information,
                MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {

                this.notifyIcon1.Visible = false;
                this.Close();
                this.Dispose();
                _player.KillPer();
                System.Environment.Exit(System.Environment.ExitCode);
            }
        }

        private void LoadFileToLst()
        {
            foreach (var item in _XmlFile.LstFiles)
            {
                ListViewItem newitem = new ListViewItem(item.FileName);
                newitem.Tag = item;
                lstItems.Items.Add(newitem);
            }
        }

        private void FrmMaim_Load(object sender, EventArgs e)
        {
            _capture.Start();


            _XmlFile.InitFile();
            this.notifyIcon1.Visible = true;
            LoadFileToLst();

            foreach (var item in _XmlFile.LstAutoFiles.OrderBy(p => p.Index))
            {
                ListViewItem newitem = new ListViewItem(item.FileName);
                newitem.Tag = item;

                lstAuto.Items.Add(newitem);
            }

            this.WindowState = FormWindowState.Minimized;
            _player.AutoPlay(_XmlFile.LstAutoFiles);


        }

        private void btnScan_Click(object sender, EventArgs e)
        {
            _XmlFile.ScanFiles();
            lstItems.Clear();
            LoadFileToLst();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {

        }

        private void btnClear_Click(object sender, EventArgs e)
        {

        }

        private void lstItems_ItemCheck(object sender, ItemCheckEventArgs e)
        {

        }

        private void lstItems_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (lstItems.SelectedItems.Count > 0)
            {
                var selItem = lstItems.SelectedItems[0];
                SwfFile file = selItem.Tag as SwfFile;
                if (file != null)
                {
                    _player.PlayFile(file);

                }

            }
        }

        private void btnDele_Click(object sender, EventArgs e)
        {
            if (lstAuto.SelectedItems.Count == 0) return;
            var item = lstAuto.SelectedItems[0];
            lstAuto.Items.Remove(item);
            ReflashAutoFile();

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                Process processes = Process.GetCurrentProcess();
                string name = processes.ProcessName;
                if (checkBox1.Checked == true)
                {
                    RegistryKey R_local = Registry.LocalMachine;//RegistryKey R_local = Registry.CurrentUser;  
                    RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    R_run.SetValue(name, Application.ExecutablePath);
                    R_run.Close();
                    R_local.Close();
                }
                else
                {
                    RegistryKey R_local = Registry.LocalMachine;//RegistryKey R_local = Registry.CurrentUser;  
                    RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    R_run.DeleteValue(name, false);
                    R_run.Close();
                    R_local.Close();
                }

                //GlobalVariant.Instance.UserConfig.AutoStart = isAuto;  
            }
            catch (Exception)
            {
                //MessageBoxDlg dlg = new MessageBoxDlg();  
                //dlg.InitialData("您需要管理员权限修改", "提示", MessageBoxButtons.OK, MessageBoxDlgIcon.Error);  
                //dlg.ShowDialog();  
                MessageBox.Show("您需要管理员权限修改", "提示");
            }
        }

        private void txtTime_ValueChanged(object sender, EventArgs e)
        {
            ConfigureAppConfig.AppSettingsSave("PlayTime", txtTime.Value.ToString());
            _player.PlayTime = (int)txtTime.Value;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            this.notifyIcon1.Visible = true;
            this.Hide();
        }

        private void lstAuto_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (lstAuto.SelectedItems.Count > 0)
            {
                var selItem = lstAuto.SelectedItems[0];
                SwfFile file = selItem.Tag as SwfFile;
                if (file != null)
                {
                    _player.PlayFile(file, true);
                }

            }
        }

        private void lstItems_ItemDrag(object sender, ItemDragEventArgs e)
        {
            this.DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void lstItems_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void lstAuto_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void lstAuto_ItemDrag(object sender, ItemDragEventArgs e)
        {
            this.DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void lstAuto_DragOver(object sender, DragEventArgs e)
        {
            Point ptScreen = new Point(e.X, e.Y);
            Point pt = lstAuto.PointToClient(ptScreen);
            ListViewItem item = lstAuto.GetItemAt(pt.X, pt.Y);
            if (item != null)
                item.Selected = true;
        }

        private void lstAuto_DragDrop(object sender, DragEventArgs e)
        {
            ListViewItem draggedItem = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
            if (draggedItem.ListView == lstItems)
            {
                foreach (var item in lstAuto.Items)
                {
                    if (((ListViewItem)item).Text == draggedItem.Text)
                        return;
                }
            }


            Point ptScreen = new Point(e.X, e.Y);
            Point pt = lstAuto.PointToClient(ptScreen);
            ListViewItem TargetItem = lstAuto.GetItemAt(pt.X, pt.Y);//拖动的项将放置于该项之前  
            if (TargetItem == null)
                lstAuto.Items.Add((ListViewItem)draggedItem.Clone());
            else
                lstAuto.Items.Insert(TargetItem.Index, (ListViewItem)draggedItem.Clone());

            lstAuto.Items.Remove(draggedItem);

            ReflashAutoFile();
        }

        private void ReflashAutoFile()
        {
            if (_player.AutoPlayFiles == null)
                _player.AutoPlayFiles = new List<SwfFile>();
            _player.AutoPlayFiles.Clear();
            foreach (var item in lstAuto.Items)
            {
                ListViewItem vitem = item as ListViewItem;
                SwfFile file = vitem.Tag as SwfFile;
                file.Index = vitem.Index;
                _player.AutoPlayFiles.Add(file);
            }
        }

        private void btnSaveAuto_Click(object sender, EventArgs e)
        {
            _XmlFile.ReflashAutoXml(_player.AutoPlayFiles);
            MessageBox.Show("保存成功！");
        }

        private void btnStar_Click(object sender, EventArgs e)
        {
            List<SwfFile> lstFile = new List<SwfFile>();
            foreach (var item in lstAuto.Items)
            {
                ListViewItem vitem = item as ListViewItem;
                SwfFile file = vitem.Tag as SwfFile;
                file.Index = vitem.Index;
                lstFile.Add(file);
            }
            _player.AutoPlay(lstFile);
        }

        int WM_KEYDOWN = 256;
        int WM_SYSKEYDOWN = 260;
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            //if (msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN)
            //{
            //    switch (keyData)
            //    {
            //        case Keys.Up:
            //            _player.PlayBefor();
            //            break;
            //        case Keys.Down:
            //            _player.PlayAfter();
            //            break;
            //    }
            //}
            return base.ProcessCmdKey(ref msg, keyData);
        }

    }
}
